<?php
class Admin_Model_UsersAdminMapper {

	protected $_dbTable;

	public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }

        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }

        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Admin_Model_DbTable_UsersAdmin');
        }

        return $this->_dbTable;
    }

	public function save(Admin_Model_TableColumn_UsersAdmin $user) {
		try {
			$now = date('Y-m-d H:i:s');

			$data = array(
				'id'					=> $user->getId(),
				'email'					=> $user->getEmail(),
				'password'				=> $user->getPassword(),
				'role'					=> $user->getRole(),
				'ho_ten'				=> $user->getHo_ten(),
				'hinh_anh'				=> $user->getHinh_anh(),
				'ngay_sinh'				=> date_format(date_create_from_format('d-m-Y', $user->getNgay_sinh()), 'Y-m-d'),
				'dien_thoai'			=> $user->getDien_thoai(),
				'dang_nhap_cuoi'		=> $user->getDang_nhap_cuoi(),
				'kich_hoat'				=> $user->getKich_hoat(),
				'ngay_tao'				=> $user->getNgay_tao(),
				'nguoi_tao'				=> $user->getNguoi_tao(),
				'ngay_cap_nhat'			=> $user->getNgay_cap_nhat(),
				'nguoi_cap_nhat'		=> $user->getNguoi_cap_nhat(),
				'thanh_pho_phu_trach'	=> $user->getThanh_pho_phu_trach(),
				'da_xoa'				=> $user->getDa_xoa()
			);

			if (0 == $user->getId()) {
				unset($data['id']);
				$data['ngay_tao'] = $now;
				$data['ngay_cap_nhat'] = $now;
				$data['kich_hoat'] = 1;
				$data['da_xoa'] = 0;
				$data['dang_nhap_cuoi'] = $now;
				$this->getDbTable()->insert($data);
			} else {
				$data['ngay_cap_nhat'] = $now;
				$this->getDbTable()->update($data, array('id = ?' => $user->getId()));
			}
		} catch (Exception $e) {
			return false;
		}

		return true;
	}

	public function countItem($arrParam, $exclude) {
		$ssFilter = $arrParam['ssFilter'];

		$table = $this->getDbTable();
		$select = $table->select()->setIntegrityCheck(false);
		$select->from(array('usr' => 'tb_users_admin'), 'COUNT(*) AS totalItem');
		$select->joinLeft(array('qh'=> 'tb_quyen_han'),	'usr.role=qh.id');
		$select->joinLeft(array('tp'=> 'tb_thanh_pho'),	'usr.thanh_pho_phu_trach=tp.id');

		$state = $ssFilter['state'];
		$keywords = $ssFilter['keywords'];
		$select->where($table->getAdapter()->quoteInto('usr.da_xoa=?', $state));
		$select->where('usr.email			LIKE ? OR ' .
					   'usr.ho_ten			LIKE ? OR ' .
					   'usr.dien_thoai		LIKE ? OR ' .
					   '(qh.ten_quyen_han IS NOT NULL AND qh.ten_quyen_han LIKE ?) OR ' .
					   '(tp.ten			  IS NOT NULL AND tp.ten		   LIKE ?)', '%' . $keywords . '%');

		if ($exclude != null) {
			$select->where($table->getAdapter()->quoteInto('usr.id NOT IN (?)', $exclude));
		}

		$resultSet = $table->fetchAll($select);
		$array = $resultSet->toArray();
		return $array[0]['totalItem'];
	}

	public function fetch($arrParam, $exclude) {
		$paginator = $arrParam['paginator'];
		$ssFilter = $arrParam['ssFilter'];
		$table = $this->getDbTable();
	
		$select = $table->select()->setIntegrityCheck(false);
		$select->from(array('usr' => 'tb_users_admin'), '*');
		$select->joinLeft(array('adm1'	=> 'tb_users_admin'),	'usr.nguoi_tao=adm1.id',			'ho_ten AS ten_nguoi_tao');
		$select->joinLeft(array('adm2'	=> 'tb_users_admin'),	'usr.nguoi_cap_nhat=adm2.id',		'ho_ten AS ten_nguoi_cap_nhat');
		$select->joinLeft(array('qh'	=> 'tb_quyen_han'),		'usr.role=qh.id',					'ten_quyen_han');
		$select->joinLeft(array('tp'	=> 'tb_thanh_pho'),		'usr.thanh_pho_phu_trach=tp.id',	'ten AS ten_thanh_pho');

		$state = $ssFilter['state'];
		$keywords = $ssFilter['keywords'];
		$col = $ssFilter['col'];
		$order = $ssFilter['order'];
		$select->where($table->getAdapter()->quoteInto('usr.da_xoa=?', $state));
		$select->where('usr.email			LIKE ? OR ' .
					   'usr.ho_ten			LIKE ? OR ' .
					   'usr.dien_thoai		LIKE ? OR ' .
					   '(qh.ten_quyen_han IS NOT NULL AND qh.ten_quyen_han LIKE ?) OR ' .
					   '(tp.ten			  IS NOT NULL AND tp.ten		   LIKE ?)', '%' . $keywords . '%');

		if ($exclude != null) {
			$select->where($table->getAdapter()->quoteInto('usr.id NOT IN (?)', $exclude));
		}

		$select->order($col . ' ' . $order);

		$page = $paginator['currentPage'];
		$rowCount = $paginator['itemCountPerPage'];
		$start = (int) $rowCount * ($page - 1);

		$select->limit($rowCount, $start);
		return $this->processResultSet($table->fetchAll($select)->toArray(), 'view');
	}

	public function fetchAll($query, $option) {
		if ($query === NULL) {
			$resultSet = $this->getDbTable()->fetchAll();

		} else {
			$table = $this->getDbTable();
			$select = $table->select();
			$select->from($table)->where($query);
			$resultSet = $this->getDbTable()->fetchAll($select);
		}

		return $this->processResultSet($resultSet->toArray(), $option);
	}

	private function processResultSet($resultSet, $option) {
		$entries = array();

		if ($option == 'view') {
			foreach ($resultSet as $row) {
				$entry = new Admin_Model_TableColumn_UsersAdmin($row);
				$entries[] = $entry;
			}

		} else {
			foreach ($resultSet as $row) {
				$entries[] = $row;
			}
		}

		return $entries;
	}

	// Update trang thai ẩn|hiện
	public function deleteItems($ids, $state, $currentUser) {
		try {
			$data = array(
					'da_xoa' 			=> $state,
					'ngay_cap_nhat' 	=> date('Y-m-d H:i:s'),
					'nguoi_cap_nhat' 	=> $currentUser
			);
	
			if (is_array($ids)) {
				foreach ($ids as $id) {
					$data['id'] = trim($id);
					$this->getDbTable()->update($data, array('id = ?' => $id));
				}
	
			} else {
				$data['id'] = trim($ids);
				$this->getDbTable()->update($data, array('id = ?' => $ids));
			}
	
		} catch (Exception $e) {
			return false;
		}
	
		return true;
	}
	
	public function getPersonalInformation($id) {
		$table = $this->getDbTable();
		$select = $table->select()->setIntegrityCheck(false);
		$select->from(array('usr' => 'tb_users_admin'), '*');
		$select->joinLeft(array('qh' => 'tb_quyen_han'), 'usr.role=qh.id', 'ten_quyen_han');
		$select->joinLeft(array('tp' => 'tb_thanh_pho'), 'usr.thanh_pho_phu_trach=tp.id', 'ten AS ten_thanh_pho');
		$select->where('usr.id = ?', $id);
		return $this->processResultSet($table->fetchAll($select)->toArray(), 'view');
	}
	
	public function getLastId() {
		return $this->getDbTable()->getAdapter()->lastInsertId();
	}
	
	public function updateLoginDate($id) {
		try {
			$data = array('dang_nhap_cuoi' => date('Y-m-d H:i:s'));
			$this->getDbTable()->update($data, array('id = ?' => $id));
		} catch (Exception $e) {
			return false;
		}
	
		return true;
	}
	
}